/*
 * AD8302.c
 *
 *  Created on: 2021年6月19日
 *      Author: Rupert
 */
#include "AD8302.h"

#include "adc.h"
#include <math.h>

#define V_REF (2.5)

#define V_CP_mV (900)
#define Rf_Islp_mV (600)
#define Rf_Ipha_mV (10)

static float getADCValue(ADC_HandleTypeDef* hadc)
{
	uint16_t adc_code;
	HAL_ADC_Start(hadc);
	HAL_ADC_PollForConversion(hadc, 100);
	if(HAL_IS_BIT_SET(HAL_ADC_GetState(hadc), HAL_ADC_STATE_REG_EOC))
	{
		adc_code = HAL_ADC_GetValue(hadc);
	}
	float voltage = adc_code * V_REF / 4096;
	return voltage;
}

// ADC1 检查增益检波结果
double AD8302_GetMagnification()
{
	float adc_value = 0;
	for (uint8_t i = 0; i < 10; i++)
	{
		adc_value += getADCValue(&hadc1);
	}
	adc_value /= 10;
	float voltage_mV = 1000 * adc_value;
//	double mag = (voltage_mV - (double)V_CP_mV) / (double)Rf_Islp_mV;
//	mag = pow(10, mag);
	return voltage_mV;
}

// ADC2 检查相位检波结果 单位：degree
double AD8302_GetPhase()
{

	float adc_value = 0;
	for (uint8_t i = 0; i < 10; i++)
	{
		adc_value += getADCValue(&hadc2);
	}
	adc_value /= 10;
	float voltage_mV = 1000 * adc_value;
//	double phase = 90 - (voltage_mV - (double)V_CP_mV) / (double)Rf_Ipha_mV;
	return voltage_mV;
}

